import { Form, Input, Radio, ColorPicker } from 'antd'
import { forwardRef, useImperativeHandle } from 'react'
import { useModel } from '@umijs/max'
import './PageSettingCom.less'

function PageSettingCom({}, ref) {
  const [pageSettingFormRef] = Form.useForm() // 页面设置表单
  const { setPageSettingData } = useModel('ActivityEditor')

  // 处理表单提交
  const handleFinish = async () => {
    await pageSettingFormRef.validateFields()
    const values = await pageSettingFormRef.getFieldsValue()
    return values
  }

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    handleFinish
  }))

  // 监听 form 表单值变化
  const onValuesChange = (changedValues, allValues) => {
    setPageSettingData(allValues)
  }

  // 颜色选择器
  const CustomColorPicker = ({ value, onChange }) => {
    return (
      <ColorPicker
        value={value}
        onChangeComplete={color => {
          onChange(color.toHexString())
        }}
      />
    )
  }

  return (
    <div className='page_setting_com'>
      <Form
        onValuesChange={onValuesChange}
        style={{ marginTop: '20px' }}
        preserve={false}
        form={pageSettingFormRef}
        name='page_setting'
        initialValues={{
          pageName: '活动专题页',
          backgroundColor: 'default'
        }}
      >
        <Form.Item name='pageName' label='页面名称 : ' rules={[{ required: true, message: '请输入页面名称' }]}>
          <Input placeholder='请填写页面名称' allowClear maxLength={5} />
        </Form.Item>
        <Form.Item name='backgroundColor' label='背景颜色 : ' rules={[{ required: true, message: '请选择背景色' }]}>
          <Radio.Group>
            <Radio value={'default'}>默认背景色</Radio>
            <Radio value={'#ff6787'}>自定义背景色</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          wrapperCol={{ span: 24 }}
          shouldUpdate={(prevValues, curValues) => prevValues.backgroundColor !== curValues.backgroundColor}
          noStyle
        >
          {() => {
            let isDefault = pageSettingFormRef.getFieldValue('backgroundColor') === 'default'
            return (
              <>
                {isDefault ? null : (
                  // 颜色选择器
                  <Form.Item
                    name='backgroundColor'
                    label='自定义背景颜色'
                    rules={[{ required: true, message: '请选择背景颜色' }]}
                  >
                    <CustomColorPicker />
                  </Form.Item>
                )}
              </>
            )
          }}
        </Form.Item>
      </Form>
    </div>
  )
}

export default forwardRef(PageSettingCom)
